const env = process.env.NODE_ENV
require('es6-promise').polyfill();
require('isomorphic-fetch');

//取queryString
export function getParameterByName(name, url) {
    if (!url) {
      url = window.location.href;
    }
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

//DateTransformer
export function utcToDate(timestamp) {
    timestamp = Number(timestamp+'000');
    let y = new Date(timestamp).getFullYear(),
        m = new Date(timestamp).getMonth()+1,
        d = new Date(timestamp).getDate(),
        h = new Date(timestamp).getHours(),
        mm = new Date(timestamp).getMinutes();
    m = m < 10 ? '0' + m : m;
    mm = mm < 10 ? '0' + mm : mm;
    h = h < 10 ? '0' + h : h;
    if(y === new Date().getFullYear()) return m + '月'+d+'日 '+h+':'+mm;
    else return y + '年' + m + '月' + d+ '日 ' + h + ':' +mm;
}

// myalert
export function myAlert(txt) {
    let div0 = document.createElement('div'),
        div = document.createElement('div');
    div.innerHTML = txt;
    div.classList.add('my-alert');
    div0.appendChild(div);
    div0.classList.add('my-alert-container');
    document.querySelector('body').appendChild(div0);
    setTimeout(()=>{
        document.querySelector('body').removeChild(div0);
    },1500)
}

export function loadMore({
    el = '',
    cb = function() {}
}) {
    this.el = el;
    this.cb = cb;
    this.loading = false;
    loadMore.prototype.toEnd = function() {
        // documen.body.scrollTop在chomre下居然一直为0！
        var scrollTop = this.el ? this.el.scrollTop : window.scrollY,
            pageHeight = this.el ? this.el.getBoundingClientRect().height : window.innerHeight,
            scrollHeight = this.el ? this.el.scrollHeight : document.body.scrollHeight;
        if (scrollTop + pageHeight > scrollHeight - 5) {
            if (this.loading) return;
            this.loading = true;
            this.cb();
        }
    }
    loadMore.prototype.open = function() {
        this.listener = this.toEnd.bind(this);
        this.el ? this.el.addEventListener('scroll', this.listener, false) : window.addEventListener('scroll', this.listener, false);
    }
    loadMore.prototype.close = function() {
        this.el ? this.el.removeEventListener('scroll', this.listener, false) : window.removeEventListener('scroll', this.listener, false);
    }
}

export function handleHistory(router, historyUrl) {
    const thisUrl = document.url
    history.pushState(null, null, thisUrl);
    window.addEventListener('popstate', function () {
        if(document.url === thisUrl) router.replace(historyUrl);
    });
}

function request(data) {

    function serialize(obj) {
        var str = [];
        for(var p in obj)
          if (obj.hasOwnProperty(p)) {
            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
          }
        return str.join("&");
    }

    const fetchPromise = new Promise((res,reject) => {
       
            const baseURL = env === 'development' ? 'https://easy-mock.com/mock/5a0a567bb31e3216824d6a7d/shopping' : 'http://zhedacxz.com/shopping_zhou/php/PcApi';
            const reqURL = env === 'development' ? `${baseURL}/${data.name}` : baseURL
            const credentials = env === 'development' ? '' : 'include'
    
            let headers = new Headers();
    
            headers.append("Content-Type", "application/x-www-form-urlencoded");
            fetch(reqURL, {
                method: 'POST',
                headers,
                credentials,
                body: serialize(data)
            }).then(r => r.json()).then(obj => res(obj)).catch(err => reject(err));
       
    })

    const abortPromise = new Promise((res, reject) => {
        setTimeout(reject, 1000000, 'abort promise')
        // 网络连接问题
    })

    return Promise.race([fetchPromise, abortPromise])
}

export async function myFetch (data) {
    try {
        const res = await request(data)
        return res
    } catch (err) {
        const msg = err === 'timeout' ? '网络连接异常，请稍后刷新重试' : '后台出错了~'
        return { success: false, msg }
    }
}